import Vue from "vue";
import { apis } from '@/api/index.js';
import { getScopeMap } from '@/common/utils/utils.js'

const cacheKeyAuthorization = 'AUTHORIZATION';
const cacheKeyCookie = 'COOKIE';

export const user = {
	namespaced: true,
	state: {
		userInfo: {},
		authorization: '',
		cookie: ''
	},
	mutations: {
		setCacheData(state) {
			const data = uni.getStorageSync(cacheKeyAuthorization);
			if (data) {
				state.authorization = data;
			}
			const cookie = uni.getStorageSync(cacheKeyCookie);
			if (cookie) {
				state.cookie = cookie;
			}
		},
		// 设置用户信息
		setUserInfo(state, data) {
			if (data) {
				state.userInfo = data;
			}
		},
		// 设置授权信息
		setAuthorization(state, data) {
			if (data) {
				state.authorization = data
				uni.setStorage({
					key: cacheKeyAuthorization,
					data: data
				})
			}
		},
		// 设置授权信息
		setCookie(state, data) {
			if (data) {
				state.cookie = data
				uni.setStorage({
					key: cacheKeyCookie,
					data: data
				})
			}
		},
		clear(state) {
			state.userInfo = {};
		},
		clearToken(state) {
			uni.removeStorageSync(cacheKeyAuthorization);
			state.authorization = '';
		}
	},
	actions: {
		getUserInfo({ state, commit }) {
			return apis.user.getInfo()
				.then(res => {
					const userInfo = res;
					commit('setUserInfo', userInfo);
					return userInfo
				})
		}
	}
}
